package com.zzyl.nursing.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.nursing.service.WechatService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * TODO
 *
 * @Author XS
 * @Date 2025/10/22 15:43
 */
@Service
public class WechatServiceImpl implements WechatService {

    //小程序ID
    @Value("${weChat.appId}")
    private String appId;

    //小程序密钥
   @Value("${weChat.appSecret}")
    private String appSecret;
    //获取手机号API地址
    private static final String POST_PHONE_API_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";

    //小程序登录API地址
    private static final String GET_OPEN_ID_URL = "https://api.weixin.qq.com/sns/jscode2session";

    //获取访问Token的API地址
    private static final String GET_ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token";



    /**
     * 获取小程序基本参数
     * @return
     */
    public Map<String, Object> getAppConfig(){
        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("appid",appId);
        paramMap.put("secret",appSecret);
        return paramMap;
    }
    /**
     * 根据临时登录凭证code获取OpenId
     *
     * @param code
     */
    @Override
    public String getOpenId(String code) {

        Map<String, Object> paramMap = this.getAppConfig() ;

        paramMap.put("js_code", code);
        paramMap.put("grant_type", "authorization_code");
        String result = HttpUtil.get(GET_OPEN_ID_URL, paramMap);
        if ( StrUtil.isBlank(result)) {
            throw new BaseException("获取OpenId失败");
        }
        //转为JSON对象
        JSONObject jsonObject = JSONObject.parseObject(result);
        return jsonObject.getString("openid");
    }

    /**
     * 根据临时凭证码（手机号获取专用凭证码，非openId凭证码）获取手机号
     *
     * @param code
     */
    @Override
    public String getPhone(String code) {
        String accessToken = this.getAccessToken();
        Map<String, Object> paramMap =new HashMap<>();
        paramMap.put("code",code);
        String result = HttpUtil.post(POST_PHONE_API_URL + accessToken, JSON.toJSONString(paramMap));
        if ( StrUtil.isBlank(result)) {
            throw new BaseException("获取手机号失败");
        }
        JSONObject jsonObject = JSONObject.parseObject(result);
        return jsonObject.getJSONObject("phone_info").getString("phoneNumber");


    }



    /**
     * 获取小程序访问Token
     * @return
     */
    public String getAccessToken(){
        Map<String, Object> paramMap = this.getAppConfig() ;
        paramMap.put("grant_type", "client_credential");
        String result = HttpUtil.get(GET_ACCESS_TOKEN_URL, paramMap);
        if ( StrUtil.isBlank(result)) {
            throw new BaseException("获取Token失败");
        }
        JSONObject jsonObject = JSONObject.parseObject(result);
        return jsonObject.getString("access_token");
    }
}
